package com.enation.app.javashop.core.promotion.newcomer.service.impl;

import com.enation.app.javashop.core.promotion.newcomer.model.dos.NewcomerDO;
import com.enation.app.javashop.core.promotion.newcomer.model.dos.NewcomerGoodsDO;
import com.enation.app.javashop.core.promotion.newcomer.model.enums.NewcomerStatusEnums;
import com.enation.app.javashop.core.promotion.newcomer.model.vos.QueryNewcomerVO;
import com.enation.app.javashop.core.promotion.newcomer.service.NewcomerGoodsManager;
import com.enation.app.javashop.core.promotion.newcomer.service.NewcomerManager;
import com.enation.app.javashop.core.promotion.tool.model.dos.PromotionGoodsDO;
import com.enation.app.javashop.core.promotion.tool.model.enums.PromotionTypeEnum;
import com.enation.app.javashop.core.promotion.tool.service.PromotionGoodsManager;
import com.enation.app.javashop.core.statistics.StatisticsException;
import com.enation.app.javashop.core.statistics.util.DateUtil;
import com.enation.app.javashop.core.trade.order.model.enums.YesOrNoEnums;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.security.model.Seller;
import com.enation.app.javashop.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: zhou
 * @Date: 2021/2/25
 * @Description: 新人购活动
 */
@Service
public class NewcomerManagerImpl implements NewcomerManager {

    @Autowired
    @Qualifier("systemDaoSupport")
    private DaoSupport daoSupport;

    @Autowired
    private PromotionGoodsManager promotionGoodsManager;

    @Autowired
    private NewcomerGoodsManager newcomerGoodsManager;

    @Override
    public Page<NewcomerDO> queryNewcomerList(QueryNewcomerVO queryNewcomerVO) {
        StringBuilder sql = new StringBuilder("select * from es_newcomer ");

        List<Object> termList = new ArrayList<>();

        sql.append(" where is_delete=? and seller_id = ?");
        termList.add(YesOrNoEnums.NO.getIndex());
        termList.add(UserContext.getSeller().getSellerId());

        if (!StringUtil.isEmpty(queryNewcomerVO.getNewcomerName())) {
            sql.append(" and newcomer_name like ? ");
            termList.add("%" + queryNewcomerVO.getNewcomerName() + "%");
        }

        if (queryNewcomerVO.getStatus() != null) {
            sql.append(" and `status` =? ");
            termList.add(queryNewcomerVO.getStatus());
        }

        // 按时间查询
        Long startTime = queryNewcomerVO.getStartTime();
        if (!ObjectUtils.isEmpty(startTime)) {
            sql.append(" and start_time >= ? ");
            termList.add(startTime);
        }
        Long endTime = queryNewcomerVO.getEndTime();
        if (!ObjectUtils.isEmpty(endTime)) {
            sql.append(" and end_time <= ? ");
            termList.add(endTime);
        }

        sql.append(" order by create_time desc");
        return this.daoSupport.queryForPage(sql.toString(), queryNewcomerVO.getPageNo(), queryNewcomerVO.getPageSize(),
                NewcomerDO.class, termList.toArray());
    }

    @Override
    public void addOrUpdateNewcomer(NewcomerDO newcomerDO) {
        if (newcomerDO == null) {
            throw new StatisticsException("新增或修改新人购活动参数错误");
        }

        // 默认状态为下线
        newcomerDO.setStatus(NewcomerStatusEnums.NEW.getIndex());

        Seller seller = UserContext.getSeller();
        if (newcomerDO.getNewcomerId() == null) {
            // 新增
            newcomerDO.setSellerId(seller.getSellerId());
            newcomerDO.setSellerName(seller.getSellerName());
            newcomerDO.setCreateTime(DateUtil.getDateline());
            newcomerDO.setIsDelete(YesOrNoEnums.NO.getIndex());
            daoSupport.insert(newcomerDO);
        } else {
            int newcomerId=newcomerDO.getNewcomerId();
            Long startTime=newcomerDO.getStartTime();
            Long endTime=newcomerDO.getEndTime();

            // 如果活动起始时间有变化，需要更新新人活动商品的起始时间
            NewcomerDO oldNewcomer=this.daoSupport.queryForObject(NewcomerDO.class,newcomerDO.getNewcomerId());
            if(!oldNewcomer.getStartTime().equals(startTime)||!oldNewcomer.getEndTime().equals(endTime)){
                // 更新商品的开始和结束时间
                String updateSql="UPDATE es_promotion_goods SET start_time=? , end_time=?  WHERE promotion_type = ? and activity_id=?";
                this.daoSupport.execute(updateSql,startTime,endTime,PromotionTypeEnum.NEWCOMER,newcomerId);
            }

            // 修改
            newcomerDO.setUpdateTime(DateUtil.getDateline());
            daoSupport.update(newcomerDO, newcomerId);
        }
    }

    @Override
    @Transactional(value = "systemTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void deleteNewcomer(Integer newcomerId) {

        if (newcomerId == null || newcomerId == 0) {
            throw new StatisticsException("参数异常");
        }
        NewcomerDO newcomerDO = this.daoSupport.queryForObject(NewcomerDO.class, newcomerId);
        if (newcomerDO == null) {
            throw new StatisticsException("活动不存在");
        }
        Seller seller = UserContext.getSeller();
        if (!seller.getSellerId().equals(newcomerDO.getSellerId())) {
            throw new StatisticsException("没有权限操作非本店铺的活动");
        }
        if (newcomerDO.getStatus() == NewcomerStatusEnums.ONLINE.getIndex()) {
            throw new StatisticsException("不能删除已上线的活动");
        }

        // 1、删除新人购活动
        String newcomerSql = "update es_newcomer set is_delete = ? , update_time = ? where newcomer_id = ?";
        this.daoSupport.execute(newcomerSql, YesOrNoEnums.YES.getIndex(), DateUtil.getDateline(), newcomerId);

        // 2、删除活动关联商品
        deleteNewcomerGoods(newcomerId);
    }

    @Override
    public void onOffLine(Integer newcomerId, Integer status) {

        // 如果是上线活动，判断是否已经有已上线的活动
        if (status == NewcomerStatusEnums.ONLINE.getIndex()) {
            Seller seller = UserContext.getSeller();
            String querySql = "select * from es_newcomer where seller_id = ? and `status` = ? and end_time > ?";
            List<NewcomerDO> newcomerDOList = this.daoSupport.queryForList(querySql, NewcomerDO.class, seller.getSellerId(),
                    NewcomerStatusEnums.ONLINE.getIndex(), DateUtil.getDateline());
            if (!CollectionUtils.isEmpty(newcomerDOList)) {
                List<String> names = newcomerDOList.stream().map(NewcomerDO::getNewcomerName).collect(Collectors.toList());
                throw new StatisticsException("活动【" + StringUtil.listToString(names, "，") + "】已上线，同时只能有一个活动在线！");
            }

            // 添加活动商品
            batchAddPromotionGoods(newcomerGoodsManager.getNewcomerGoodsList(newcomerId));

        }else if(status == NewcomerStatusEnums.OFFLINE.getIndex()){
            deleteNewcomerGoods(newcomerId);
        }

        // 修改活动上下线状态
        String newcomerSql = "update es_newcomer set `status` = ?, update_time = ? where newcomer_id = ?";
        this.daoSupport.execute(newcomerSql, status, DateUtil.getDateline(), newcomerId);
    }

    // 删除活动关联商品
    private void deleteNewcomerGoods(Integer newcomerId){
        String newcomerGoodsSql = " select * from es_newcomer_goods where newcomer_id = ?";
        List<NewcomerGoodsDO> newcomerGoodsDOList = this.daoSupport.queryForList(newcomerGoodsSql, NewcomerGoodsDO.class, newcomerId);
        if (!CollectionUtils.isEmpty(newcomerGoodsDOList)) {
            String deleteGoodsSql = "update es_newcomer_goods set is_delete = ? where newcomer_id = ?";
            this.daoSupport.execute(deleteGoodsSql, YesOrNoEnums.YES.getIndex(), newcomerId);
        }

        promotionGoodsManager.deleteByActivityIds(new ArrayList<>(newcomerId), PromotionTypeEnum.NEWCOMER);
    }

    // 添加活动关联商品
    private void batchAddPromotionGoods(List<NewcomerGoodsDO> newcomerGoodsDOList) {
        if (CollectionUtils.isEmpty(newcomerGoodsDOList)) {
            throw new StatisticsException("参数异常");
        }

        NewcomerDO newcomerDO = this.daoSupport.queryForObject(NewcomerDO.class, newcomerGoodsDOList.get(0).getNewcomerId());
        long startTime = newcomerDO.getStartTime();
        long endTime = newcomerDO.getEndTime();
        List<PromotionGoodsDO> promotionGoodList = new LinkedList<>();
        for (NewcomerGoodsDO newcomerGoodsDO : newcomerGoodsDOList) {
            PromotionGoodsDO promotion = new PromotionGoodsDO();
            promotion.setTitle("新人购");
            promotion.setSellerId(newcomerGoodsDO.getSellerId());
            promotion.setActivityId(newcomerGoodsDO.getNewcomerId());
            promotion.setGoodsId(newcomerGoodsDO.getGoodsId());
            promotion.setProductId(newcomerGoodsDO.getSkuId());
            promotion.setPromotionType(PromotionTypeEnum.NEWCOMER.name());
            promotion.setNum(newcomerGoodsDO.getSoldQuantity());
            promotion.setPrice(newcomerGoodsDO.getSalesPrice());
            promotion.setStartTime(startTime);
            promotion.setEndTime(endTime);
            promotionGoodList.add(promotion);
        }
        promotionGoodsManager.batchInsert(promotionGoodList);
    }
}
